#include "head.h"

void get_all_info(char* path,char* result,int netfd){
    DIR* dir=opendir(path);
    if(dir==NULL){
        char* p1="the address ";
        char* p2="is error\n";
        strcat(result,p1);
        strcat(result,path);
        strcat(result,p2);
        return ;
    }
    struct dirent* fileinfo;
    char formatinfo[]="DIRECTORY: ";
    strcat(result,formatinfo);
    strcat(result,path);
    strcat(result,"\n");
    strcat(result,"-----------------------------------------------------------\n");
    char nameinfo[]="FILE NAME: ";
    char typeinfo[]="FILE TYPE: ";
    
    while((fileinfo=readdir(dir))!=NULL){
        strcat(result,nameinfo);
        strcat(result,fileinfo->d_name);
        if(strlen(fileinfo->d_name)<4){
            strcat(result,"\t\t\t");
        }
        else if(strlen(fileinfo->d_name)>=4 && (strlen(fileinfo->d_name))<12){
            strcat(result,"\t\t");
        }
        else{
            strcat(result,"\t");
        }
        strcat(result,typeinfo);
        if(fileinfo->d_type==DT_UNKNOWN){
            strcat(result,"unknown type");
        }
        else if(fileinfo->d_type==DT_REG){
            strcat(result,"regular");
        }
        else if(fileinfo->d_type==DT_DIR){
            strcat(result,"directory type");
        }
        else if(fileinfo->d_type==DT_FIFO){
            strcat(result,"pipe file");
        }
        else if(fileinfo->d_type==DT_SOCK){
            strcat(result,"SOCKET FILE");
        }
        else if(fileinfo->d_type==DT_CHR){
            strcat(result,"character device file");
        }
        else{
            strcat(result,"other files");
        }
        strcat(result,"\n");
    }
    strcat(result,"-----------------------------------------------------------\n");

}

void lsFunc(char* arg,int netfd,stack1_t* dir){
    char result[8192];
    char path[256];
    //支持在当前目录下查看内容
    travel_stack(*dir,path);
    get_all_info(path,result,netfd);
    int ret=0;
    //send(netfd,&ret,sizeof(int),MSG_NOSIGNAL);
    int result_length=strlen(result);
    send(netfd,&result_length,sizeof(int),MSG_NOSIGNAL);
    send(netfd,result,result_length,MSG_NOSIGNAL);
}
